<script setup lang="ts">
import { getCode } from "@/api/user";
import { message } from "@/utils/message";
import { isEmail, isPhone } from "@pureadmin/utils";

interface FormItemProps {
  type: number;
  value?: string;
  code?: string;
}
interface FormProps {
  formInline: FormItemProps;
}
const props = withDefaults(defineProps<FormProps>(), {
  formInline: () => ({
    type: 1,
    value: "",
    code: ""
  })
});
const { t } = useI18n();
const newform = ref(props.formInline);
const _time = ref();
const _num = ref(60);
async function _getCode() {
  if (newform.value.type == 2) {
    if (!newform.value.value || !isPhone(newform.value.value))
      return message(t("login.purePhoneCorrectReg"), {
        type: "error"
      });
  } else {
    if (!newform.value.value || !isEmail(newform.value.value))
      return message(t("login.pureEmailCorrectReg"), {
        type: "error"
      });
  }
  await getCode(newform.value.type, newform.value.value);
  _time.value = setInterval(() => {
    if (!_num.value) {
      clearInterval(_time.value);
      _num.value = 60;
      return;
    }
    _num.value -= 1;
  }, 1000);
}
</script>

<template>
  <el-form label-width="75px">
    <el-form-item v-show="newform.type === 1" :label="$t('user.email')">
      <el-input
        v-model="newform.value"
        :placeholder="$t('login.pureEmailReg')"
      />
    </el-form-item>
    <el-form-item v-show="newform.type === 2" :label="$t('user.phone')">
      <el-input
        v-model="newform.value"
        :placeholder="$t('login.purePhoneReg')"
      />
    </el-form-item>
    <el-form-item :label="$t('login.pureVerifyCode')">
      <el-input
        v-model="newform.code"
        :placeholder="$t('login.pureVerifyCodeReg')"
      >
        <template #append>
          <el-button :disabled="_num != 60" @click="_getCode">{{
            _num == 60 ? $t("login.pureGetVerifyCode") : `${_num}s`
          }}</el-button>
        </template>
      </el-input>
    </el-form-item>
  </el-form>
</template>
